#include "wordexporter.h"
#include <QAxObject>
#include <QFile>
#include <QDir>

bool WordExporter::exportToWord(const QStringList &codePages, const QString &outputPath)
{
    QAxObject *word = new QAxObject("Word.Application");
    if (!word->isNull()) {
        word->setProperty("Visible", false);
        
        QAxObject *documents = word->querySubObject("Documents");
        QAxObject *document = documents->querySubObject("Add()");
        
        // 设置页面格式
        QAxObject *pageSetup = document->querySubObject("PageSetup");
        pageSetup->setProperty("TopMargin", 36.0);     // 0.5英寸
        pageSetup->setProperty("BottomMargin", 36.0);  // 0.5英寸
        pageSetup->setProperty("LeftMargin", 54.0);    // 0.75英寸
        pageSetup->setProperty("RightMargin", 54.0);   // 0.75英寸
        
        // 设置行号
        QAxObject *lineNumbering = pageSetup->querySubObject("LineNumbering");
        lineNumbering->setProperty("Active", true);
        lineNumbering->setProperty("CountBy", 1);
        lineNumbering->setProperty("StartingNumber", 1);
        lineNumbering->setProperty("RestartMode", 1); // 每页重新开始编号
        
        // 添加代码内容
        QAxObject *selection = word->querySubObject("Selection");
        
        // 设置文档默认字体和段落格式
        QAxObject *font = selection->querySubObject("Font");
        font->setProperty("Name", "Consolas");
        font->setProperty("Size", 9.0);
        
        QAxObject *paragraphFormat = selection->querySubObject("ParagraphFormat");
        paragraphFormat->setProperty("LineSpacingRule", 0); // 固定行距
        paragraphFormat->setProperty("LineSpacing", 12.0);  // 12磅行距
        paragraphFormat->setProperty("SpaceBefore", 0.0);
        paragraphFormat->setProperty("SpaceAfter", 0.0);
        
        for (int i = 0; i < codePages.size(); ++i) {
            if (i > 0) {
                selection->dynamicCall("InsertBreak(int)", 7); // 插入分页符
            }
            
            selection->dynamicCall("TypeText(const QString&)", codePages[i]);
        }
        
        // 保存文档
        QVariantList params;
        params << QDir::toNativeSeparators(outputPath) << 16;
        document->dynamicCall("SaveAs(const QString&, const int)", params);
        document->dynamicCall("Close()");
        word->dynamicCall("Quit()");
        
        delete word;
        return true;
    }
    
    delete word;
    return false;
} 